package com.example.userdemo.entity;

import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Random;
import java.util.Set;

/**
 * @Description
 * @Author liqinglin
 * @Date 2023/12/11 9:28
 */
public class RedisThread implements Runnable{
    private Jedis jedis;

    public RedisThread(Jedis jedis) {
        this.jedis = jedis;
    }

    @Override
    public void run() {
        try {
            String keyPattern = "unmarked_*";
            Set<String> keys = jedis.keys(keyPattern);
            Random random = new Random();
            ArrayList<String> list = new ArrayList<>(keys);
            int i = random.nextInt(list.size());
            String key = list.get(i);
            String script = "local count = tonumber(redis.call('GET', KEYS[1]) or 0)\n" +
                    "if count > 0 then\n" +
                    "    redis.call('DECR', KEYS[1])\n" +
                    "    if count == 1 then\n" +
                    "       redis.call('DEL', KEYS[1])\n" +
                    "       return count - 1\n" +
                    "    end\n" +
                    "    return count - 1\n" +
                    "else\n" +
                    "    redis.call('DEL', KEYS[1])\n" +
                    "    return 0\n" +
                    "end";
            Long eval = (Long) jedis.eval(script, 1, key);
            System.out.println(key + " " + eval);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}
